package service

import (
	log "ac-common-go/glog"
	"ac-julink/cache"
	"ac-julink/constants"
	"ac-julink/httpAuth"
	"ac-julink/rpcagent/wgctl"
	"ac-julink/rpcagent/wgdm"
	"ac-julink/rpcagent/wgota"
	config_http "ac-julink/tool/config_http"
	"ac-julink/tool/data"
	hsjson "ac-julink/tool/json"
	"encoding/json"
	"errors"
	"fmt"
	"strings"
	"sync"
	"time"

	"ac-julink/kafka"
	"ac-julink/manager"
	"ac-julink/mq"
	"ac-julink/rpcagent/wgmcu"
	//"ac-julink-bk/rpcagent/wgss"
	config "ac-julink/tool/config"
)

var MsgLengthLimit = 2048

func InitConfigs() {
	msgLengthLimit, b := config.GetConfigIntValue("WGNS", "msgLengthLimit")
	if b {
		MsgLengthLimit = msgLengthLimit
	}
}

var HbConf = &HbConfig{
	HbToPsMillThreshold: 60 * 1000,
	lock:                new(sync.RWMutex),
}

type HbConfig struct {
	HbToPsMillThreshold int64
	lock                *sync.RWMutex
}

func (this *HbConfig) SetConfigs(HbToPsMillThreshold int64) {
	this.lock.Lock()
	defer this.lock.Unlock()
	this.HbToPsMillThreshold = HbToPsMillThreshold
}

func (this *HbConfig) GetHbToPsMillThreshold() int64 {
	this.lock.RLock()
	defer this.lock.RUnlock()
	return this.HbToPsMillThreshold
}

// 接收数据校验,消息头和长度
func CheckMsgFormat(_msg string) (msgType string, err error) {
	//1. 首先判断消息头HS
	if !strings.HasPrefix(_msg, "HS") {
		return "", errors.New("Invalid format HS !")
	}
	//2.判断数据长度
	if len(_msg) > MsgLengthLimit || len(_msg) < 7 {
		log.Error("read data error , data is too short or too long .")
		return "", errors.New("Invalid length data !")
	}
	//3.判断结束符是否为\r\n
	if !strings.HasSuffix(_msg, "\r\n") {
		return "", errors.New("Invalid end data !")
	}
	//	heatbeat := "HS{\"id\":902}
	if strings.Contains(_msg, "902") && (strings.LastIndex(_msg, "}") == len(_msg)-3) {
		return "HEARTBEAT", err
	}
	return "", nil
}

// 消息格式:HS{json}MD5\r\n
func GetJsonMd5(_msg string) (_json, _md5 string) {
	_json = _msg[2 : len(_msg)-16-2]
	_md5 = _msg[len(_json)+2 : len(_msg)-2]
	return _json, _md5
}

// 消息格式:HS{json}SHA256\r\n
func GetJsonSha256(_msg string) (_json, _sha256 string) {
	_json = _msg[2 : len(_msg)-64-2]
	_sha256 = _msg[len(_json)+2 : len(_msg)-2]
	return _json, _sha256
}

// 验证Token,并获取wifiid信息
// 区分:101消息带wifiid字段,其它消息带token字段
func CheckToken(_json string, context *cache.SyncContext, client *manager.AcRestClient) (_wifiid string, err error) {
	log.Info("CheckToken=====>>>>>")
	log.Infof("_json:%s", _json)
	//先解析token字段,若无此字段,消息为101,解析wifiid字段
	type CheckToken struct {
		Ver     string `json:"ver"`
		WifiId  string `json:"wid"`
		Token   string `json:"token"`
		Id      int    `json:"id"`
		ProtVer string `json:"ProtVer"`
	}
	var m CheckToken
	err = json.Unmarshal([]byte(_json), &m)
	if err != nil {
		log.Errorf("%+v", err)
	} else {
		log.Infof("Id=%d,Token:%s,WifiId:%s", m.Id, m.Token, m.WifiId)
		if m.Id != 0 && m.Token == "" && m.WifiId != "" {
			log.Info("101 Auth no token")

			//EDWIN
			_wifiid = strings.ToLower(m.WifiId)
		} else {
			//直接获取到token,并验证
			if len(m.Token) == 0 {
				return "", errors.New(fmt.Sprintf("no token in uploaded json: %s", _json))
			}
			var _ret int
			_wifiid, _ret, err = httpAuth.AuthCheckToken(m.Token, client)
			if _ret != 0 || len(_wifiid) == 0 {
				log.Error("AuthCheckToken Error !")
				err = errors.New("AuthCheckToken Error")
				return "", err
			}
		}
	}
	return _wifiid, err
}

func HandleAuth(msgJson, _wifiid, _prekey, _ip string, _fdid int, context *cache.SyncContext, client *manager.AcRestClient) (reponse string, _cryptType int, err error) {
	var ver, protVer string
	var deviceVer []data.DeviceVer
	var cryptType int
	_, ver, deviceVer, protVer, err = hsjson.ParseAuthMsg(msgJson)

	// AES256CBC
	if protVer == "HENC" {
		cryptType = constants.CRYPT_AES_256_CBC
	}

	if err != nil {
		err = errors.New("ParseAuthMsg failed!")
		return "", cryptType, err
	}

	token, activated, err := client.ActivateDevice(_wifiid)

	log.Infof("ActivateDevice-> token: %s, activated: %v", token, activated)

	//1.创建token
	//var token string
	var code int
	var _json string
	//token, code, err = httpAuth.AuthCreateToken(_wifiid, ver, client)
	if !activated || len(token) == 0 || err != nil {
		log.Errorf("AuthCreateToken failed!%s,%d,%+v", _wifiid, code, err)
		//2.create Json,组装json
		_json, _ = hsjson.AuthJsonCreate(token, 1)
	} else {
		//2.create Json,组装json
		_json, _ = hsjson.AuthJsonCreate(token, 0)
		//3.ps online
		var wgpsStatus data.WGPSstats
		wgpsStatus.Wifiid = _wifiid
		wgpsStatus.WifiVersion = ver
		wgpsStatus.Stat = 1 //在线
		wgpsStatus.OwnerServer = data.Mysid
		wgpsStatus.PeerAddr = _ip
		wgpsStatus.NetId = int32(_fdid)
		wgpsStatus.Protocol = "julink1.0"
		wgpsStatus.DevVer = deviceVer // xwj add for mcu
		wgpsStatus.ProtVer = protVer

		go func() {
			err := client.WifiOnline(wgpsStatus)
			if err != nil {
				log.Errorf("WifiOnline failed! %s", _wifiid)
			}
		}()
	}

	//4.pacakage msg
	//组装HS{}MD5\r\n格式数据包
	_msgResult := data.PackageMsg(_json, _prekey)
	return _msgResult, cryptType, err
}

func HandleKey(_msgJson, _wifiid, _prekey string, context *cache.SyncContext, client *manager.AcRestClient, cryptType int) (reponse string, err error) {
	//1.获取动态密钥
	var _json, dynKey string
	var update bool
	var rootCheck = true
	var version = -1
	var fetchLatestCertInnerResp map[string]interface{}
	var m map[string]interface{}

	if err = json.Unmarshal([]byte(_msgJson), &m); err != nil {
		log.Errorf("failed to parse msg 102 to map. error: %+v", err)
	} else {
		if value, ok := m["update"]; ok && value != nil {
			update = value.(bool)
		} else {
			rootCheck = false
		}
		if value, ok := m["version"]; ok && value != nil {
			version = int(value.(float64))
		} else {
			rootCheck = false
		}
	}

	dynKey, fetchLatestCertInnerResp, err = client.GetCipheredDKey(_wifiid, cryptType, update, version)

	if err != nil {
		log.Error("GetCipheredDKey failed !")
		//2.组装json
		_json, _ = hsjson.KeyJsonCreate("", 1)
	} else {
		log.Infof("HandleKey dynKey[%s]", dynKey)
		if rootCheck {
			_json, _ = hsjson.KeyJsonCreateRootCheck(dynKey, 0, fetchLatestCertInnerResp)
		} else {
			//2.组装json
			_json, _ = hsjson.KeyJsonCreate(dynKey, 0)
		}
	}
	//3.pacakage msg,组装HS{}MD5\r\n格式数据包
	_msgResult := data.PackageMsg(_json, _prekey)
	return _msgResult, err
}

func checkIf7s(fetureCode7s, rKeyInConfig, wifiId string) bool {
	if len(fetureCode7s) == 0 || len(rKeyInConfig) == 0 {
		return false
	} else {
		flag := false
		for _, featureCode := range strings.Split(fetureCode7s, ",") {
			if strings.HasPrefix(wifiId, featureCode) {
				flag = true
				break
			}
		}

		return flag
	}
}

func HandleSysConifg(wifiid, _prekey string, client *manager.AcRestClient, cryptType int) (string, error) {
	log.Info("HandleSysConifg======>>>>")
	var errCode int
	//1. 获取系统参数
	hb := config_http.GetConfigValue("HeartbeatInterval")
	rp := config_http.GetConfigValue("ReportInterval")
	retry := config_http.GetConfigValue("RetryInterval")

	fetureCode7s := config_http.GetConfigValue("FetureCode7s")
	rKeyInConfig := config_http.GetConfigValue("RKey")

	is7s := checkIf7s(fetureCode7s, rKeyInConfig, wifiid)
	var rkey string

	if is7s {
		if rkeyRemote, err := client.CipherWithDKey(wifiid, rKeyInConfig, cryptType); err != nil {
			log.Errorf("get system parameter failed!hb(%s),rp(%s),retry(%s)", hb, rp, retry)
			errCode = 1
			return "", errors.New("failed to cipher rkey via warehouse!")
		} else {
			rkey = rkeyRemote
		}
	}

	if hb == "" || rp == "" || retry == "" {
		log.Errorf("get system parameter failed!hb(%s),rp(%s),retry(%s)", hb, rp, retry)
		errCode = 1
		return "", errors.New("get system parameter failed")
	}
	_timezone, f := config_http.GetConfigValueInt64("TimeZone")
	if !f {
		log.Errorf("get timezone(%d) failed!", _timezone)
		errCode = 1
		return "", errors.New("get timezone failed")
	}
	//3.组装json
	var _json string
	if is7s {
		if errCode == 1 {
			_json, _ = hsjson.SysParamJsonCreate7s(hb, rp, retry, int(_timezone), 1, rkey)
		} else {
			_json, _ = hsjson.SysParamJsonCreate7s(hb, rp, retry, int(_timezone), 0, rkey)
		}
	} else {
		if errCode == 1 {
			_json, _ = hsjson.SysParamJsonCreate(hb, rp, retry, int(_timezone), 1)
		} else {
			_json, _ = hsjson.SysParamJsonCreate(hb, rp, retry, int(_timezone), 0)
		}
	}

	//4.pacakage msg,组装HS{}MD5\r\n格式数据包
	_msgResult := data.PackageMsg(_json, _prekey)
	return _msgResult, nil
}

func HandleControlResult(msgJson, _wifiid, _prekey string) (err error) {
	//1. 解析JSON数据
	_, result, status, seq, errcode, devtype, cmdver, _cmdResult, err := hsjson.ParseMsgControl(msgJson)

	//2.根据一对一设备还是一拖多设备分别处理
	if devtype == data.MULTDEVICETYPE { //2.0一拖多设备,调用新接口
		retlist := make([]*wgctl.CmdExecResult_, len(_cmdResult))
		resultlist := make([]wgctl.CmdExecResult_, len(_cmdResult))
		for i, ch := range _cmdResult {
			resultlist[i].Deviceid = ch.GetDeviceid()
			resultlist[i].Retno = int32(ch.GetRetno())
			resultlist[i].Retmsg = ch.GetRetmsg()
			retlist[i] = &resultlist[i]
		}
		/*ret, err := wgctl.UploadDeviceCtlCmdResult_(_wifiid, int32(seq), retlist)
		if err != nil || ret != 0 {
			log.Errorf("UploadDeviceCtlCmdResult_ failed !ret[%d]%+v", ret, err)
		}*/
		status := ""
		cmdver := 0
		statusver := 0
		//废弃原来的http调用
		/*
			ret, err := wgctl.ReportDeviceCmdResult(_wifiid, int32(seq), retlist,status, int32(cmdver), int32(statusver))
			resultCode := int(ret.ResultCode)
			if err != nil ||resultCode!=0{
				log.Errorf("ReportDeviceCmdResult failed ! %v", err)
			} else {
				log.Infof("ReportDeviceCmdResult succ ! resultCode %d", resultCode)
			}
		*/
		//修改为kafka推送到dshd
		_mqStr, err := hsjson.KafkaJsonCreateCmdResult(_wifiid, int32(seq), retlist, status, int32(cmdver), int32(statusver))
		if err != nil {
			log.Errorf("201 KafkaJsonCreateCmdResult failed ! %+v", err)
			return err
		}
		err = kafka.ProduceMessageAsync(data.KafkaTopic201, _mqStr, _wifiid)
		if err != nil {
			log.Errorf("201 Kafka send failed ! %+v", err)
			return err
		}

	} else {
		//如果status的格式不对或没有此字段,status赋值"null",不上报状态
		if len(status) > data.CHECKSTRLEN {
			/*statusver := 0
			if data.StatusToCtlFlag == 1 { //send to ctl
				if status != "" { //xwj add 2018/12/05
					ret, err := wgctl.UploadWifiStatus(_wifiid, int64(seq), status, int32(cmdver), int32(statusver))
					if err != nil || ret != 0 {
						log.Error("UploadWifiStatus failed !")
					}
				}
			} */
			retlist := make([]*wgctl.CmdExecResult_, 1)
			resultlist := make([]wgctl.CmdExecResult_, 1)
			resultlist[0].Deviceid = ""
			resultlist[0].Retno = int32(errcode)
			resultlist[0].Retmsg = result
			retlist[0] = &resultlist[0]

			log.Infof("ReportDeviceCmdResult  errcode %d", errcode)
			log.Infof("ReportDeviceCmdResult  result %s", result)
			statusver := 0
			//废弃原来的http调用
			/*
				if status != "" {
					ret, err := wgctl.ReportDeviceCmdResult(_wifiid, int32(seq), retlist, status, int32(cmdver), int32(statusver))
					errCode := int(ret.ResultCode)
					if err != nil ||errCode!=0{
						log.Errorf("ReportDeviceCmdResult failed ! %v", err)
					} else {
						log.Infof("ReportDeviceCmdResult succ ! errCode %d", errCode)
					}
				}
			*/
			//修改为kafka推送dshd
			if status != "" {
				_mqStr, err := hsjson.KafkaJsonCreateCmdResult(_wifiid, int32(seq), retlist, status, int32(cmdver), int32(statusver))
				if err != nil {
					log.Errorf("KafkaJsonCreateCmdResult failed ! %+v", err)
					return err
				}
				err = kafka.ProduceMessageAsync(data.KafkaTopic201, _mqStr, _wifiid)
				if err != nil {
					log.Errorf("201 Ctl Kafka send failed ! %+v ,topic:[%s]", err, data.KafkaTopic201)
					return err
				} else {
					log.Infof("201  Ctl Device Status by kafka success, topic:[%]", data.KafkaTopic201)

				}
			}

		}

		/*ret, err := wgctl.UploadCtlCmdResult_(_wifiid, int32(seq), int32(errcode), result)
		if err != nil || ret != 0 {
			log.Errorf("UploadCtlCmdResult_ failed !%+v", err)
		}*/
	}
	return err
}
func HandleControlReset(msgJson, _wifiid, _prekey string) (err error) {
	//1. 解析JSON数据
	_, _seq, _err, err := hsjson.ParseMsgReset(msgJson)
	if err != nil {
		return err
	}
	ret, err := wgctl.ReportControlReset(_wifiid, _seq, _err)
	resultCode := int(ret.ResultCode)
	if err != nil || resultCode != 0 {
		log.Errorf("ReportDeviceCmdResult failed ! %v", err)
	} else {
		log.Infof("ReportDeviceCmdResult succ ! resultCode %d", resultCode)
	}

	return err
}

func HandleQueryCmd(msgJson, _wifiid, _prekey string) (err error) {
	//1. 解析JSON数据
	_, _, _, seq, devStatusList, err := hsjson.ParseMsgQuery(msgJson)

	//如果status的格式不对或没有此字段,status赋值"null",不上报状态
	if len(devStatusList[0].GetValue()) > data.CHECKSTRLEN {
		//		var retlist []*wgctl.DeviceData
		retlist := make([]*wgctl.DeviceData, len(devStatusList))
		resultlist := make([]wgctl.DeviceData, len(devStatusList))
		for i, ch := range devStatusList {
			resultlist[i].Deviceid = ch.GetDeviceId()
			resultlist[i].Value = ch.GetValue()

			retlist[i] = &resultlist[i]
		}
		if data.StatusToCtlFlag == 1 { //send to ctl
			ret, err := wgctl.UploadRefreshStatusHttp(_wifiid, int64(seq), retlist)
			if err != nil || ret.ResultCode != 0 {
				log.Errorf("UploadRefreshStatus failed !ret[%d]%+v", ret, err)
			}
		} else { //send to rabbitmq
			/*
				statusver := 0
				cmdver := 0
				statusList := make([]data.DeviceData, len(devStatusList))
				for k, ch3 := range devStatusList {
					statusList[k].SetDeviceId(ch3.GetDeviceId())
					statusList[k].SetValue(ch3.GetValue())
				}
				//发送RabbitMq消息
				_mqStr, err := hsjson.RabbitMqJsonCreate(_wifiid, _status, 0, seq, cmdver, statusver, statusList)
				if err != nil {
					log.Errorf("RabbitMqJsonCreate failed ! %+v", err)
				}
				err = mq.SendMessage(_mqStr)
				if err != nil {
					log.Errorf("RabbitMq send failed ! %+v", err)
				}
			*/
		}
	}
	return err
}
func HandleQueryVer(msgJson, _wifiid string) (err error) {
	//	1. 解析JSON数据
	//	_, ver, _type, _err, err = hsjson.ParseMsgQueryVer(msgJson)

	//ctl,report_status

	return err
}
func HandleOtaResult(msgJson, _wifiid string) (err error) {
	topic := config.GetConfigValue("WGNS", "ota_upload_queue_name")
	if len(topic) <= 0 {
		log.Errorf(" ota_upload_queue_name is null ! ")
		return
	}
	//	1. 解析JSON数据
	_, _desc, _wifiVersion, _originVersion, _targetVersion, _err, _resultCode, _policyId, err := hsjson.ParseMsgOtaResult(msgJson)
	if err != nil {
		return errors.New("Ota failed !")
	}
	err = mq.SendOTAResultToService(topic, _wifiid, _desc, _wifiVersion, _originVersion, _targetVersion, _err, _resultCode, _policyId)
	return err

}
func HandleOtaQuery(_msgJson, _wifiid, _prekey string) (reponse string, err error) {
	//1.获取升级结果
	var _wifiver, _url, _md5, _versionDesc string
	var _filesize, _updateflag, _err, _policyId, _targetedType int
	//var otaIn wgota.InWgotaCheckVerReqT
	//otaIn.DvcID = _wifiid
	//otaIn.MsgVer = 1
	//ret, err := wgota.WgotaCheckVerReq(&otaIn)
	//解析Json数据
	_, ver, languageId, err := hsjson.ParseMsgQueryOta(_msgJson)
	if err != nil {
		log.Errorf("Parse Ota query error, err:%v", err)
	}

	ret, err := wgota.WgotaCheckVerReq(_wifiid, ver, languageId)
	resultCode := int(ret.ResultCode)

	if err != nil || resultCode != 0 {
		log.Errorf("WgotaCheckVerReq failed ! %v", err)
		log.Errorf("WgotaCheckVerReq ! resultCode%d", resultCode)
	} else {
		log.Infof("WgotaCheckVerReq succ ")
		_wifiver = ret.WifiVersion
		_url = ret.Url
		_filesize = int(ret.FileSize)
		_md5 = ret.Sign
		_updateflag = int(ret.UpdateFlag)
		_versionDesc = ret.VersionDesc
		_policyId = int(ret.PolicyId)
		_targetedType = int(ret.TargetedType)
	}

	/*if err != nil || ret.GetMsgReply() != 0 {
		log.Errorf("HTTP WgotaCheckVerReq error ! %+v", err)
		_err = -1
	} else {
		_wifiver = ret.GetVer()
		_url = ret.GetAddr()
		_filesize = int(ret.GetLen())
		_md5 = ret.GetMd5()
		_updateflag = int(ret.GetUpdateFlag())
		_err = 0
	}*/
	//2.组装json
	_json, _ := hsjson.OtaQueryJsonCreate(1, _filesize, _updateflag, _err, _policyId, _wifiid, _wifiver, _md5, _url, _versionDesc, _targetedType)
	//3.pacakage msg,组装HS{}MD5\r\n格式数据包
	_msgResult := data.PackageMsg(_json, _prekey)
	return _msgResult, err
}

// xwj add for mcu upgrade begin
// Edwin: modify rpc to http direct call
func HandleMcuUpgradeResult(msgJson, _wifiid string) (err error) {
	//	1. 解析JSON数据
	_, _ver, _type, _errCode, err := hsjson.ParseMsgMcuUpgradeResult(msgJson)
	if err != nil {
		log.Error("Mcu upgrade failed !")
		return err
	}
	log.Infof("_wifiid[%s],_type[%d],_ver[%s],_errCode[%d]", _wifiid, _type, _ver, _errCode)
	err = wgmcu.FeedbackUpgradeResultHttp(_wifiid, _type, _ver, _errCode)
	if err != nil {
		log.Errorf("HandleMcuUpgradeResult call FeedbackUpgradeResultHttp failed !%+v", err)
		return err
	} else {
		log.Errorf("HandleMcuUpgradeResult call FeedbackUpgradeResultHttp succeeded!")
	}
	return nil
}

// xwj add for mcu upgrade end
func HandleDevBind(msgJson, _wifiid, _prekey string) (reponse string, err error) {
	//1.解析json数据
	_, devid, err := hsjson.ParseMsgDevBind(msgJson)
	if err != nil {
		log.Error("ParseMsgDevBind failed!")
		return "", err
	}
	//2.调用WGDM绑定设备
	errCode := -1
	var _token wgdm.Token
	var result string
	ret, err := wgdm.AddWifiDevice(&_token, _wifiid, devid)
	if err != nil {
		log.Errorf("AddWifiDevice failed ! %+v", err)
	} else {
		//errCode = int(ret.GetResultCode())
		errCode = int(ret.ResultCode)
		//result = ret.GetDesc()
	}
	//3.组装json
	_json, _ := hsjson.DevBindJsonCreate(errCode, devid, result)
	//4.pacakage msg,组装HS{}MD5\r\n格式数据包
	_msgResult := data.PackageMsg(_json, _prekey)
	return _msgResult, nil
}
func HandleDevUnBind(msgJson, _wifiid, _prekey string) (reponse string, err error) {
	//1.解析json数据
	_, devid, err := hsjson.ParseMsgDevUnBind(msgJson)
	if err != nil {
		log.Error("ParseMsgDevUnBind failed!")
		return "", err
	}
	//2.调用WGDM绑定设备
	errCode := -1
	var _token wgdm.Token
	var result string
	ret, err := wgdm.DeleteWifiDevice(&_token, _wifiid, devid)
	if err != nil {
		log.Errorf("DeleteWifiDevice failed ! %+v", err)
	} else {
		//errCode = int(ret.GetResultCode())
		errCode = int(ret.ResultCode)
		//result = ret.GetDesc()
	}
	//3.组装json
	_json, _ := hsjson.DevUnBindJsonCreate(errCode, devid, result)
	//4.pacakage msg,组装HS{}MD5\r\n格式数据包
	reponse = data.PackageMsg(_json, _prekey)
	return reponse, err
}

//	func HandleBindDevList(_wifiid, _prekey string) (reponse string, err error) {
//		var _token wgdm.Token
//		errCode := -1
//		var devids []string
//		ret, err := wgdm.GetWifiDeviceList(&_token, _wifiid)
//		if err != nil {
//			log.Errorf("GetWifiDeviceList failed!%+v", err)
//		} else {
//			devids = make([]string, len(ret.GetWifiDeviceList()))
//			errCode = int(ret.GetResult_().GetResultCode())
//			for _, ch := range ret.GetWifiDeviceList() {
//				devids = append(devids, ch.GetDeviceId())
//			}
//		}
//		//2.组装json
//		_json, _ := hsjson.BindListJsonCreate(errCode, devids)
//		//3.pacakage msg,组装HS{}MD5\r\n格式数据包
//		_msgResult := data.PackageMsg(_json, _prekey)
//		return _msgResult, err
//	}
//
//	func HandleHomeDevList(_wifiid, _prekey string) (reponse string, err error) {
//		errCode := -1
//		var devlist []data.HomeDevice
//		ret, err := wgdm.GetHomeDeviceListByWifiId(_wifiid)
//		if err != nil {
//			log.Error("GetHomeDeviceListByWifiId failed !")
//		} else {
//			errCode = int(ret.GetResult_().GetResultCode())
//			devlist = make([]data.HomeDevice, len(ret.GetDeviceList()))
//			for i, ch := range ret.GetDeviceList() {
//				devlist[i].SetDeviceId(ch.GetDeviceId())
//				devlist[i].SetWifiId(ch.GetWifiId())
//				devlist[i].SetDeviceTypeCode(ch.GetDeviceTypeCode())
//			}
//		}
//		//2.组装json
//		_json, _ := hsjson.HomeBindListJsonCreate(errCode, devlist)
//		//3.pacakage msg,组装HS{}MD5\r\n格式数据包
//		_msgResult := data.PackageMsg(_json, _prekey)
//		return _msgResult, err
//	}
func HandleDevExtInfoStore(msgJson, _wifiid, _prekey string) (reponse string, err error) {
	//1.解析数据
	_, devid, extkey, extinfo, err := hsjson.ParseMsgDevExtInfoSave(msgJson)
	if err != nil {
		log.Error("ParseMsgDevExtInfoSave failed!")
		return "", err
	}
	//参数校验
	if extkey == "" {
		log.Error("Invald Extkey ！")
		//2.组装json
		_json, _ := hsjson.DevExtInfoJsonCreate(-1, devid, extinfo)
		//3.pacakage msg,组装HS{}MD5\r\n格式数据包
		_msgResult := data.PackageMsg(_json, _prekey)
		return _msgResult, err
	}
	//2.调用wgdm存储扩展信息
	var _token wgdm.Token
	errCode := -1
	ret, err := wgdm.SaveDeviceExtendsValue(&_token, _wifiid, devid, extkey, extinfo, "", 0, 0)
	if err != nil {
		log.Errorf("SaveDeviceExtendsValue failed ! %+v", err)
	} else {
		//errCode = int(ret.GetResultCode())
		errCode = int(ret.ResultCode)
	}

	//2.组装json
	_json, _ := hsjson.DevExtInfoJsonCreate(errCode, devid, extinfo)
	//3.pacakage msg,组装HS{}MD5\r\n格式数据包
	_msgResult := data.PackageMsg(_json, _prekey)
	return _msgResult, err
}
func HandelDevReset(msgJson, _wifiid, _prekey string) (reponse string, err error) {
	//1. 解析JSON数据
	_, oprtype, err := hsjson.ParseMsgDevReset(msgJson)
	if err != nil {
		log.Errorf("ParseMsgDevReset failed !", err)
	}
	//2.调用wgdm重置设备
	errCode := -1
	ret, err := wgdm.DeviceReset(_wifiid, int32(oprtype))
	if err != nil {
		log.Error("DeviceReset failed!")
	} else {
		errCode = int(ret.ResultCode)
	}
	//2.组装json
	_json, _ := hsjson.DevResetJsonCreate(errCode, oprtype, _wifiid)
	//3.pacakage msg,组装HS{}MD5\r\n格式数据包
	_msgResult := data.PackageMsg(_json, _prekey)
	return _msgResult, err
}

/*
func HandelGetSceneList(_wifiid, _prekey string) (reponse string, err error) {
	//1.调用wgss
	errCode := -1
	var result string
	var scenelist []data.SceneIdInfo
	ret, err := wgss.GetSceneIdInfoList(_wifiid)
	if err != nil {
		log.Error("GetSceneIdInfoList failed!")
	} else {
		errCode = int(ret.GetResult_().GetResultCode())
		result = ret.GetResult_().GetDesc()
		scenelist = make([]data.SceneIdInfo, len(ret.GetSceneIdList()))
		for i, ch := range ret.GetSceneIdList() {
			scenelist[i].SetSceneId(int(ch.GetSceneId()))
			scenelist[i].SetSceneType(int(ch.GetSceneType()))
			scenelist[i].SetUpdateTime(int(ch.GetUpdatetime()))
		}
	}
	//2.组装json
	_json, _ := hsjson.HomeSceneInfoJsonCreate(errCode, result, scenelist)
	//3.pacakage msg,组装HS{}MD5\r\n格式数据包
	_msgResult := data.PackageMsg(_json, _prekey)
	return _msgResult, err
}*/
/*
func HandelGetSceneInfo(msgJson, _wifiid, _prekey string) (reponse string, err error) {
	//1.解析数据
	_, sceneids, multenable, err := hsjson.ParseMsgGetSceneInfo(msgJson)
	if err != nil {
		log.Errorf("ParseMsgGetSceneInfo failed! %+v", err)
		return "", err
	}
	//2.调用wgss
	_scendids := make([]int64, len(sceneids))
	for i, ch := range sceneids {
		_scendids[i] = int64(ch)
	}
	errCode := -1
	var result string
	var sceneinfo []data.Scene
	ret, err := wgss.GetSceneInfoList(_scendids, int32(multenable))
	if err != nil {
		log.Errorf("SaveDeviceExtendsValue failed ! %+v", err)
	} else {
		errCode = int(ret.GetResult_().GetResultCode())
		result = ret.GetResult_().GetDesc()
		sceneinfo = make([]data.Scene, len(ret.GetSceneList()))
		for i, ch := range ret.GetSceneList() {
			sceneinfo[i].SetSceneId(int(ch.GetSceneId()))
			sceneinfo[i].SetHomeId(int(ch.GetHomeId()))
			sceneinfo[i].SetSceneName(ch.GetSceneName())
			sceneinfo[i].SetSceneType(int(ch.GetSceneType()))
			sceneinfo[i].SetStatus(int(ch.GetStatus()))
			sceneinfo[i].SetUpdatetime(int(ch.GetUpdatetime()))
			sceneinfo[i].SetConSceneId(int(ch.GetConSceneId()))
			sceneinfo[i].SetConrelation(int(ch.GetConrelation()))
			cmdlist := make([]data.Cmd, len(ch.CmdList))
			for j, ch := range ch.CmdList {
				cmdlist[j].SetCmdOrder(int(ch.GetCmdOrder()))
				cmdlist[j].SetCmdId(int(ch.CmdId))
				cmdlist[j].SetCmdParam(int(ch.CmdParam))
				cmdlist[j].SetDeviceId(ch.GetDeviceId())
				cmdlist[j].SetWifiId(ch.GetWifiId())
				cmdlist[j].SetDelayTime(int(ch.GetDelayTime()))
			}
			sceneinfo[i].SetCmdList(cmdlist)

			sceneconditionlist := make([]data.SceneCondition, len(ch.SceneConditionList))
			for k, ch := range ch.SceneConditionList {
				sceneconditionlist[k].SetSceneConditionId(int(ch.GetSceneConditionId()))
				sceneconditionlist[k].SetDeviceId(ch.GetDeviceId())
				sceneconditionlist[k].SetWifiId(ch.GetWifiId())
				sceneconditionlist[k].SetStatusValue(int(ch.GetStatusValue()))
				sceneconditionlist[k].SetOperateType(int(ch.GetOperateType()))
				sceneconditionlist[k].SetStatusParamValue(int(ch.GetStatusParamValue()))
			}
			sceneinfo[i].SetSceneConditionList(sceneconditionlist)

			validtimelist := make([]data.SceneValidTime, len(ch.GetValidTimeList()))
			for l, ch := range ch.GetValidTimeList() {
				validtimelist[l].SetStartTime(ch.GetStartTime())
				validtimelist[l].SetEndTime(ch.GetEndTime())
			}
			sceneinfo[i].SetValidTimeList(validtimelist)
		}
	}
	//2.组装json
	_json, _ := hsjson.SceneInfoQueryJsonCreate(errCode, result, sceneinfo)
	//3.pacakage msg,组装HS{}MD5\r\n格式数据包
	_msgResult := data.PackageMsg(_json, _prekey)
	return _msgResult, err
}
*/
func HandelConfigDataResult(msgJson, _wifiid string) (err error) {
	//1. 解析JSON数据
	_id, _, _seq, _dataType, _data, _devid, _err, err := hsjson.ParseMsConfigDataResult(msgJson)
	if err != nil {
		log.Errorf("ParseMsgDevReset failed !", err)
		return err
	}

	topic := config.GetConfigValue("WGNS", "wgconfig_upload_queue_name")
	if len(topic) <= 0 {
		log.Errorf(" wgconfig_upload_queue_name is null ! ")
		return
	}
	mq.SendConfigDataResultToService(topic, _wifiid, _id, _seq, _dataType, _data, _devid, _err)
	return err
}

func HandelConfigDataReport(msgJson, _wifiid string) (err error) {
	//1. 解析JSON数据
	_id, _, _seq, _dataType, _data, _devid, err := hsjson.ParseMsConfigDataReport(msgJson)
	if err != nil {
		log.Errorf("ParseMsgDevReset failed !", err)
		return err
	}

	topic := config.GetConfigValue("WGNS", "wgconfig_upload_queue_name")
	if len(topic) <= 0 {
		log.Errorf(" wgconfig_queue_name is null ! ")
		return
	}
	mq.SendConfigDataToService(topic, _wifiid, _id, _seq, _dataType, _data, _devid)
	return err
}

func HandelCommonDataResult(msgJson, _wifiid string, msgId int) (err error) {
	topic := config.GetConfigValue("WGNS", "wgcommon_upload_queue_name")
	if len(topic) <= 0 {
		log.Errorf(" wgcommon_upload_queue_name is null ! ")
		return
	}
	err = mq.SendCommonDataResultToService(topic, _wifiid, msgJson, msgId)
	return err
}

func HandleReportStatus(msgJson, _wifiid, _prekey string) error {

	//1. 解析JSON数据
	_, status, errcode, devtype, seq, cmdver, statusver, _devstatuslist, err := hsjson.ParseMsgStatusReport(msgJson)
	if errcode != 0 {
		return errors.New("ReportStatus invalid !")
	}

	var retlist []*wgctl.DeviceData
	var resultlist []wgctl.DeviceData
	//2.根据一对一设备还是一拖多设备分别处理
	if devtype == data.MULTDEVICETYPE { //2.0一拖多设备,调用新接口
		//2.调用WGCTL的RPC接口上报状态
		retlist = make([]*wgctl.DeviceData, len(_devstatuslist))
		resultlist = make([]wgctl.DeviceData, len(_devstatuslist))
		for i, ch := range _devstatuslist {
			resultlist[i].Deviceid = ch.GetDeviceId()
			resultlist[i].Value = ch.GetValue()

			retlist[i] = &resultlist[i]
		}
		/*ret, err := wgctl.UploadWifiDeviceStatus(_wifiid, int64(seq), retlist, int32(cmdver), int32(statusver))
		if err != nil || ret != 0 {
			log.Error("UploadWifiDeviceStatus failed !")
			return err
		}*/
	} else {
		if status != "" {
			/*ret, err := wgctl.UploadWifiStatus(_wifiid, int64(seq), status, int32(cmdver), int32(statusver))
			if err != nil || ret != 0 {
				log.Error("UploadWifiStatus failed !")
				return err
			}*/
			retlist = make([]*wgctl.DeviceData, 1)
			resultlist = make([]wgctl.DeviceData, 1)
			resultlist[0].Deviceid = ""
			resultlist[0].Value = status
			retlist[0] = &resultlist[0]

		}

	}

	/*
		     	ret, err := wgctl.ReportDeviceStatus(_wifiid, int64(seq), retlist, int32(cmdver), int32(statusver))
			    resultCode := int(ret.ResultCode)
				if err != nil ||resultCode!=0{
					log.Errorf("ReportDeviceStatus failed ! %v", err)
				} else {
					log.Infof("ReportDeviceStatus succ ! resultCode %d", resultCode)
				}
	*/

	_mqStr, err := hsjson.KafkaJsonCreateStatus(_wifiid, int64(seq), retlist, int32(cmdver), int32(statusver))
	if err != nil {
		log.Errorf("901 KafkaJsonCreateStatus failed ! %+v", err)
		return err
	}
	log.Infof("_wifiid:%s", _wifiid)
	err = kafka.ProduceMessageAsync(data.KafkaTopic901, _mqStr, _wifiid)
	if err != nil {
		log.Errorf("901 Kafka send failed ! %+v, topic:[%s]", err, data.KafkaTopic901)
		return err
	} else {
		log.Infof("901  ReportDeviceStatus by kafka success, topic:[%]", data.KafkaTopic901)
	}

	return err
}

// xiaohong add for 903
func HandleReportUpdateStatus(msgJson, _wifiid, _prekey string) (result string, err error) {

	//1. 解析JSON数据
	_, status, errcode, devtype, seq, cmdver, statusver, _devstatuslist, err := hsjson.ParseMsgStatusReportUpdate(msgJson)
	if errcode != 0 {
		return "", errors.New("ReportStatus invalid !")
	}

	var retlist []*wgctl.DeviceData
	var resultlist []wgctl.DeviceData
	//2.根据一对一设备还是一拖多设备分别处理
	if devtype == data.MULTDEVICETYPE { //2.0一拖多设备,调用新接口
		//2.调用WGCTL的RPC接口上报状态
		retlist = make([]*wgctl.DeviceData, len(_devstatuslist))
		resultlist = make([]wgctl.DeviceData, len(_devstatuslist))
		for i, ch := range _devstatuslist {
			resultlist[i].Deviceid = ch.GetDeviceId()
			resultlist[i].Value = ch.GetValue()

			retlist[i] = &resultlist[i]
		}

	} else {
		if status != "" {
			retlist = make([]*wgctl.DeviceData, 1)
			resultlist = make([]wgctl.DeviceData, 1)
			resultlist[0].Deviceid = ""
			resultlist[0].Value = status
			retlist[0] = &resultlist[0]

		}

	}
	/* 放弃http调用
	ret, err := wgctl.ReportDeviceUpdateStatus(_wifiid, int64(seq), retlist, int32(cmdver), int32(statusver))
	resultCode := int(ret.ResultCode)
	log.Infof("ReportDeviceStatus  resultCode %d", resultCode)
	if err != nil ||resultCode!=0{
		log.Errorf("ReportDeviceStatus failed ! %v", err)
	} else {
		log.Infof("ReportDeviceStatus succ ! resultCode %d", resultCode)
	}*/
	//改为kafka推送903状态
	var _json string
	_mqStr, err := hsjson.KafkaJsonCreateStatus(_wifiid, int64(seq), retlist, int32(cmdver), int32(statusver))
	if err != nil {
		log.Errorf("903 KafkaJsonCreateStatus failed ! %+v", err)
		_json, _ = hsjson.KeyJsonCreate("", 1)
	}
	log.Infof("_wifiid:%s", _wifiid)
	err = kafka.ProduceMessageAsync(data.KafkaTopic903, _mqStr, _wifiid)
	if err != nil {
		log.Errorf("903 Kafka send failed ! %+v,topic:[%s]", err, data.KafkaTopic903)
		//2.组装json
		_json, _ = hsjson.KeyJsonCreate("", 1)
	} else {
		log.Infof("903  ReportDeviceStatus by kafka success, topic:[%]", data.KafkaTopic903)
		//2.组装json
		_json, _ = hsjson.UpdateStatusCreate("", 0)
	}
	//3.pacakage msg,组装HS{}MD5\r\n格式数据包
	_msgResult := data.PackageMsg(_json, _prekey)
	return _msgResult, err

}

// xiaohong add end
func HandleHeartBeatReport(_wifiid, _ip string, _port int, context *cache.SyncContext, client *manager.AcRestClient, cryptType int, time101 int64) (reponse string, err error) {
	_json, err := hsjson.HeartBeatJsonCreate()
	if err != nil {
		log.Errorf("HeartBeatJsonCreate failed: %v", err)
		return "", err
	}

	now := time.Now().UnixNano() / int64(time.Millisecond)

	if now-time101 > HbConf.GetHbToPsMillThreshold() {
		//ps online
		var wgpsStatus data.WGPSstats
		wgpsStatus.Wifiid = _wifiid
		wgpsStatus.WifiVersion = ""
		wgpsStatus.Stat = 1 //在线
		wgpsStatus.OwnerServer = data.Mysid
		wgpsStatus.PeerAddr = _ip
		wgpsStatus.NetId = int32(_port)
		wgpsStatus.Protocol = "julink1.0"
		wgpsStatus.DevVer = nil

		if cryptType == constants.CRYPT_AES_256_CBC {
			wgpsStatus.ProtVer = "HENC"
		}
		err = client.WifiOnline(wgpsStatus)
		if err != nil {
			err = errors.New("WifiOnline failed !")
			return "", err
		}
	}

	return _json, err
}

func HandelDeviceOffline(_wifiid, _ip string, _fdid int, context *cache.SyncContext, client *manager.AcRestClient, cryptTypeFromSession int) {
	//3.ps online
	//client := manager.GetClientFacade()
	var wgpsStatus data.WGPSstats
	wgpsStatus.Wifiid = _wifiid
	wgpsStatus.WifiVersion = ""
	wgpsStatus.Stat = 2 //不在线
	wgpsStatus.OwnerServer = data.Mysid
	wgpsStatus.PeerAddr = _ip
	wgpsStatus.NetId = int32(_fdid)
	wgpsStatus.Protocol = "julink1.0"
	wgpsStatus.DevVer = nil
	if cryptTypeFromSession == constants.CRYPT_AES_256_CBC {
		wgpsStatus.ProtVer = "HENC"
	}
	err := client.WifiOnline(wgpsStatus)
	if err != nil {
		log.Error("WifiOnline failed !")
	}
}
